'use strict';
/** 游戏的消息 */
module.exports.run = function(d,s){
    if(s.U.gamename){
        const gm = require("./game" + s.U.gamename);
        gm.run(d,s);
    }else if(d[2].gametp){ //游戏里面登录
        const gcf = require("../config/gamelist.json");
        if(d[2].gametp in gcf){
            const gm = require("./game" + gcf[d[2].gametp]);
            gm.run(d,s);
        }
    }
}

/** 登录事件 */
module.exports.login = function(s){
    const bs = require("../module/base"), gcf = require("../config/gamelist.json"), task = require("./task");
    bs.DB.query("SELECT gdata,bag,boxs,task FROM games WHERE userid = $1 AND tp = $2",(rs)=>{
        if(!s.U.game){
            if(rs.rows.length){
                s.U.game = rs.rows[0].gdata;
                s.U.bag = rs.rows[0].bag;
                s.U.box = rs.rows[0].boxs;
                s.U.task = rs.rows[0].task;
            }else{
                s.U.bag = {};
                s.U.box = [];
                s.U.task = {0:{},1:{},2:{},rw:{},lt:Date.now()};
            }
        }
        //兼容老数据
        if(!s.U.task['2']) s.U.task['2'] = {};
        
        if(s.U.gametp in gcf){
            s.U.gamename = gcf[s.U.gametp];
            const gm = require("./game" + s.U.gamename);
            gm.login && gm.login(s);
            task.events(3, s);
        }
        //发送登录完成
        bs.send(s, "[0,100]");
    },[s.U.uid, s.U.gametp]);
}

/** 获得道具 */
module.exports.getitem = function(s, it){
    if(s.U.gamename){
        const gm = require("./game" + s.U.gamename);
        gm.getitem && gm.getitem(s, it);
    }
}

/** 游戏退出 */
module.exports.loginout = function(s){
    if(s.U.gamename){
        const gm = require("./game" + s.U.gamename);
        gm.loginout && gm.loginout(s);
    }
    this.save(s);
}

/** 保存数据 */
module.exports.save = function(s){
    const bs = require("../module/base");
    bs.DB.query("INSERT INTO games VALUES($1,$2,$3,$4,$5,$6) ON CONFLICT (userid,tp) DO UPDATE SET gdata = $3, bag = $4, boxs = $5, task = $6",(rs)=>{
    },[s.U.uid, s.U.gametp, JSON.stringify(s.U.game), JSON.stringify(s.U.bag), JSON.stringify(s.U.box), JSON.stringify(s.U.task)]);
}

/** 游戏服务器关闭 */
module.exports.exit = function(){
    let gcf = require("../config/gamelist.json");
    for(let k in gcf){
        if(k == "notes") continue;
        let gm = require("./game" + gcf[k]);
        gm.exit && gm.exit();
    }
}